package at.jku.novellbedsidedevice.datasource.calllog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import at.jku.novellbedsidedevice.datasource.AbstractDataSource;
import at.jku.novellbedsidedevice.datasource.calllog.CallLogDataObject.CallType;

public class CallLogDatasource extends AbstractDataSource<CallLogDataObject> {

	private Context context;

	public CallLogDatasource(Context context) {
		this.context = context;
	}

	@Override
	public List<CallLogDataObject> getData() {
		ArrayList<CallLogDataObject> list = new ArrayList<CallLogDataObject>();

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);
		long yesterday = cal.getTimeInMillis();
		cal.add(Calendar.DATE, 1);
		long tomorrow = cal.getTimeInMillis();

		final String[] projection = null;
		final String selection = android.provider.CallLog.Calls.DATE + " < ? AND " + android.provider.CallLog.Calls.DATE + " > ?";
		final String[] selectionArgs = new String[] { Long.toString(tomorrow), Long.toString(yesterday) };
		final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
		Cursor cursor = null;
		try {
			cursor = context.getContentResolver().query(Uri.parse("content://call_log/calls"), projection, selection, selectionArgs, sortOrder);
			while (cursor.moveToNext()) {
				String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
				String callName = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));
				Date callDate = new Date(cursor.getLong(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE)));
				int callType = cursor.getInt(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
				list.add(new CallLogDataObject(callDate, callNumber, callName, CallType.toCallType(callType)));
			}
		} catch (Exception ex) {
			Log.e("NBSD", "ERROR: " + ex.toString());
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return list;
	}
}
